package capricornus.components.utils.displayneartips
{
	import capricornus.core.StageManager;
	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.geom.Point;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;
	
	[Event(name="hide", type="capricornus.components.utils.displayneartips.DisplayNearEvent")]
	public class DisplayNearTipsController extends EventDispatcher
	{
		private var _dict:Dictionary = new Dictionary();
		
		private var _dis:DisplayObject;
		
		private var _displayTime:Number = 5;;
		
		public function DisplayNearTipsController( dis:DisplayObject )
		{
			_dis = dis;
			init();
		}
		
		private function init():void
		{
			_dict[_dis] = new DisplayNearList();
		}
		
		public function get list():DisplayNearList
		{
			return _dict[_dis];
		}
		
		/**
		 * 
		 * @param value 秒
		 * 
		 */		
		public function set displayTime( value:Number ):void
		{
			_displayTime = value;
		}
		
		public function show( item:DisplayObject, direct:int=1, maxLen:int=3, parent:DisplayObjectContainer=null, removeOnComplete:Boolean=false ):void
		{
			var dis:DisplayObject = _dis;
			
			var di:DisplayNearItem = new DisplayNearItem( _displayTime );
			di.addItem( item );
			
			var dl:DisplayNearList = _dict[dis];
			if( dl==null )
			{
				dl = new DisplayNearList();
				_dict[dis] = dl;
			}
			if( removeOnComplete )
			{
				if( !dl.hasEventListener( DisplayNearEvent.HIDE ) )
				{
					dl.addEventListener( DisplayNearEvent.HIDE, onRemove, false, 0, true );
				}
			}
			dl.addItem( di, direct );
			
			if( dl.parent==null )
			{
				if( parent != null )
				{
					parent.addChild( dl );
				}
				else
				{
					StageManager.instance.stage.addChild( dl );
				}
			}
			
			var pt:Point = dis.localToGlobal( new Point() );
			if( parent != null )
			{
				pt = parent.globalToLocal( pt );
			}
			var rect:Rectangle = dis.getBounds( dis );
			dl.x = int(pt.x + rect.x);
			if( direct==DisplayNearTipsDirection.UP )
			{
				dl.y = int(pt.y + rect.y - 4);
			}
			else
			{
				dl.y = int(pt.y + rect.y + dis.height + 4);
			}
		}
		
		private function onRemove( e:Event ):void
		{
			var dl:DisplayNearList = e.currentTarget as DisplayNearList;
			dl.removeEventListener( DisplayNearEvent.HIDE, onRemove );
			
			if( _dict[_dis] != null )
			{
				dispatchEvent( new DisplayNearEvent( DisplayNearEvent.HIDE ) );
				
				delete _dict[_dis];
			}
		}
	}
}



